package com.ybt.heartratem.common.app;

import android.content.Context;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Build;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.RequiresApi;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.google.gson.Gson;
import com.ybt.heartratem.R;
import com.ybt.heartratem.common.CrashHandler;
import com.ybt.heartratem.common.entity.TeacherInfo;
import com.ybt.heartratem.moudle.MainActivity;

import java.io.File;
import java.io.IOException;

import me.goldze.mvvmhabit.BuildConfig;
import me.goldze.mvvmhabit.base.BaseApplication;
import me.goldze.mvvmhabit.crash.CaocConfig;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;

public class MyApplication extends BaseApplication {
    private final static String TAG = MyApplication.class.getSimpleName();
    private static MyApplication instance = null;
    public static Context context;
    public static TeacherInfo teacher;
    private SerialHelper serialHelper;

    public static MyApplication getInstance() {
        return instance;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onCreate() {
        super.onCreate();
        //是否开启打印日志
        context = this;
        KLog.init(BuildConfig.DEBUG);
        registerReceiver(new BootBroadcastReceiver(), new IntentFilter(BootBroadcastReceiver.ACTION));
        teacher = new Gson().fromJson(Injection.aasDataRe().getLoginUser(), TeacherInfo.class);

        try {
            initSerialConfig();
            serialHelper.open();
            ToastUtils.showLong("串口打开成功");
            KLog.e("串口打开成功");
        } catch (Exception e) {
            e.printStackTrace();
            KLog.e("串口打开报错:" + Log.getStackTraceString(e));
        }

        //初始化全局异常崩溃
        initCrash();
        // 异常捕获及日志记录
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
        ImagePipelineConfig config = ImagePipelineConfig.newBuilder(this)
                .setDownsampleEnabled(true)
                .build();

        Fresco.initialize(this, config);
    }

    private void initCrash() {
        CaocConfig.Builder.create()
                .backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) //背景模式,开启沉浸式
                .enabled(true) //是否启动全局异常捕获
                .showErrorDetails(true) //是否显示错误详细信息
                .showRestartButton(true) //是否显示重启按钮
                .trackActivities(true) //是否跟踪Activity
                .minTimeBetweenCrashesMs(2000) //崩溃的间隔时间(毫秒)
                .errorDrawable(R.mipmap.ic_launcher) //错误图标
                .errorActivity(MainActivity.class) //崩溃后的错误activity
                .apply();
    }

    private void initSerialConfig() {
        KLog.e("初始化串口业务");
        serialHelper = new SerialHelper("/dev/ttyS4", 9600) {
            @Override
            protected void onDataReceived(ComBean paramComBean) {
                byte[] bytes = new byte[5];
                int k = -1;
                for (int i = 5; i < 10; i++) {
                    k++;
                    bytes[k] = paramComBean.bRec[i];
                }
                String receiveContent = bytes2Hex(bytes);
                if (!TextUtils.isEmpty(receiveContent)) {
                    KLog.e(receiveContent);
                    AppController.getInstance().postOnRefreshListener(String.valueOf(Double.parseDouble(hexToString(receiveContent)) * 1000));
                }
            }
        };

        serialHelper.setStickPackageHelper(is -> {
            try {
                int available = is.available();
                if (available > 0) {
                    byte[] buffer = new byte[available];
                    int size = is.read(buffer);
                    if (size > 0) {
                        return buffer;
                    }
                } else {
                    SystemClock.sleep(50);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        });
    }

    public String hexToString(String hex) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hex.length(); i += 2) {
            String output = hex.substring(i, i + 2);
            int decimal = Integer.parseInt(output, 16);
            sb.append((char) decimal);
        }
        return sb.toString();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    private static final char[] HEXES = {
            '0', '1', '2', '3',
            '4', '5', '6', '7',
            '8', '9', 'A', 'B',
            'C', 'D', 'E', 'F'
    };

    public static String bytes2Hex(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(HEXES[(b >> 4) & 0x0F]);
            hex.append(HEXES[b & 0x0F]);
        }
        return hex.toString();
    }

    public static String byteArrayToAscii(byte[] bytes) {
        StringBuilder asciiBuilder = new StringBuilder();
        for (byte b : bytes) {
            int value = b & 0xFF; // 将byte转换为无符号整数
            asciiBuilder.append(value);
            asciiBuilder.append(" "); // 在数字之间添加空格
        }
        return asciiBuilder.toString().trim(); // 去除末尾的空格
    }
}
